package com.xinzhi.service.impl;

import com.xinzhi.config.MD5Utils;
import com.xinzhi.mapper.SetPasswordMapper;
import com.xinzhi.pojo.User;
import com.xinzhi.service.ISetPasswordService;
import com.xinzhi.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

@Service
public class SetPasswordServiceImpl implements ISetPasswordService {
    @Autowired
    private SetPasswordMapper setPasswordMapper;

    // 设置密码
    @Override
    public Result setPassword(String phone, String password, String quePassword) {
        System.out.println(phone+" "+password+" "+quePassword);
        if(phone == null || password == null || quePassword == null)
            return Result.error("您输入的信息不能为空");
        if(!isValidPassword(password)){
            return Result.error("密码格式不正确");
        }
        if(!quePassword.equals(password))
            return Result.error("两次输入的密码不一致,请重新输入");
        String md3pwd = MD5Utils.MD5Upper(password);
//        String md3pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        return setPasswordMapper.setPassword(phone,md3pwd) > 0 ? Result.ok("密码设置成功") : Result.error("密码设置失败");

    }

    //修改密码
    @Override
    public Result updatePassword(String phone, String oldPassword, String newPassword, String qrPassword) {
        System.out.println(phone+" "+oldPassword+" "+newPassword+" "+qrPassword);
        if(phone == null || oldPassword == null || newPassword == null || qrPassword == null)
            return Result.error("您输入的信息不能为空");
        if(!isValidPassword(oldPassword))
            return Result.error("请输入正确的原密码");
        String md5old = MD5Utils.MD5Upper(oldPassword);
        User userByPhone = setPasswordMapper.getUserByPhone(phone);
        if(!md5old.equals(userByPhone.getPassword()))
            return Result.error("请输入正确的原密码");
        if(!isValidPassword(newPassword))
            return Result.error("密码输入格式不正确");
        if(oldPassword.equals(newPassword))
            return Result.error("新密码不能与原密码相同");
        if(!newPassword.equals(qrPassword))
            return Result.error("两次输入的密码不一致,请重新输入");
        String md5new = MD5Utils.MD5Upper(newPassword);
        return setPasswordMapper.updatePassword(phone,md5new) > 0 ? Result.ok("修改成功") : Result.error("修改失败");
    }

    @Override
    public User getUserByPhone(String phone) {
        return setPasswordMapper.getUserByPhone(phone);
    }

    //判断密码是否合规
    @Override
    public boolean isValidPassword(String password) {
        // 使用正则表达式验证密码格式（8-12位数字和字母）
        return password.matches("^(?=.*[0-9])(?=.*[a-zA-Z])(.{8,20})$");
    }
}
